﻿// SMIL is a community project available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// View the project and the latest code at http://smil.codeplex.com/


using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using System.Data;
using System.ComponentModel;

namespace SMIL.Client.WP
{
    [Guid("6589775f-5fd3-4da0-aa4f-d08bdfe82ae1")]
    public class SMILClient : System.Web.UI.WebControls.WebParts.WebPart, IWebPartRow
    {
        
        DataTable dt = null;
        System.Web.UI.WebControls.GridView grid = null;

        protected override void OnLoad(EventArgs e)
        {
            ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
            if (scriptManager == null)
            {
                scriptManager = new ScriptManager();
                Controls.Add(scriptManager);
            }            
            
        }
        
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            
            
            ClientScriptManager cs = Page.ClientScript;// Include the required javascript file.
            
            if (!cs.IsClientScriptIncludeRegistered("sl_javascript"))
                cs.RegisterClientScriptInclude(this.GetType(), "sl_javascript", "~/_controltemplates/SMIL/Silverlight.js");
     
            if (!cs.IsClientScriptIncludeRegistered("spsl_javascript"))
                cs.RegisterClientScriptInclude(this.GetType(), "spsl_javascript", "~/_controltemplates/SMIL/SpSilverlight.js");
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            #region POSTBACK
            if (Page.IsPostBack)
            {
                string id = Page.Request["kongoselected"] as string;

                if (!string.IsNullOrEmpty(id))
                {
                    CreateDataTable();
                    InsertRow(int.Parse(id));
                    GetWPConnectFieldProvider();
                }
            }
            #endregion
                                   
            try
            {

                SMIL.Client.WP.SMILUC uc = (SMIL.Client.WP.SMILUC)Page.LoadControl("~/_controltemplates/SMIL/SMIL.Client.WP.ascx");
                uc.SPWeb = SPContext.Current.Web.Url;                
                uc.XAPFile = "/_controltemplates/smil/smil.client.wpxap.xap";
                #region SMIL map change                
                if (!string.IsNullOrEmpty(myXAPChoice))
                    uc.XAPFile = myXAPChoice;
                #endregion
                uc.Host = "http://" + SPContext.Current.Web.Site.HostName + ":" + SPContext.Current.Web.Site.Port.ToString() + "/_layouts/SPGeoRss.asmx";
                uc.CredentialsKey = System.Configuration.ConfigurationManager.AppSettings["SMIL.BingMap.CredentialsKey"];
                Controls.Add(uc);               
      
            }
            catch (Exception ex)
            {
                Controls.Add(new Label() { Text = ex.Message + " Missing SMIL.BingMap.CredentialsKey in Web.config?" });
            }

        }
        
        
        void InsertRow(int i)
        {
            if (dt.Rows != null && dt.Rows.Count == 1)
            {
                dt.Rows.RemoveAt(0);
            }

            DataRow row = dt.NewRow();
            row[0] = i;
            dt.Rows.Add(row);
        }


        void CreateDataTable()
        {
            dt = new DataTable();
            DataColumn col2 = new DataColumn();
            col2.DataType = typeof(int);
            col2.ColumnName = "id";
            dt.Columns.Add(col2);
        }

        [ConnectionProvider("id", "connectionPoint1", AllowsMultipleConnections=true)]
        public IWebPartRow GetWPConnectFieldProvider()
        {
            return this;
        }

        public void GetRowData(RowCallback callback)
        {
            if (dt != null)
            {
                callback(dt.DefaultView[0]);
            }

            else
            {
                callback(null);
            }
        }
        
        public PropertyDescriptorCollection Schema
        {
	        get 
            {
                if (dt != null)
                    return TypeDescriptor.GetProperties(dt.DefaultView[0]);

                CreateDataTable();
                InsertRow(0);
                return TypeDescriptor.GetProperties(dt.DefaultView[0]);
            }

        }
        #region Properties
        private string myXAPChoice = string.Empty;
        [Category("SMIL Map Change"),
        Personalizable(PersonalizationScope.User),
        WebBrowsable(true), WebDisplayName("Enter XAP file name here, i e /_controltemplates/smil/YOUR .XAP FILE or http://localhost/Shared%20Documents/YOUR .XAP FILE"),
        WebDescription("SMIL map change")]
        public string MyXAPChoice
        {
            get { return myXAPChoice; }
            set { myXAPChoice = value; }
        }
        #endregion
    }
}
